package demo1;
import java.io.*;
import java.net.*;
public class duihua {
        public static void main(String[] args) {
            try {
                Socket socket = new Socket("127.0.0.1", 8081);
                System.out.println("已连接到服务器");

                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                // 创建线程，用于接收服务器消息
                new Thread(() -> {
                    try {
                        String message;
                        while ((message = in.readLine()) != null) {
                            System.out.println("服务器说：" + message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();

                // 创建线程，用于读取控制台输入并发送到服务器
                new Thread(() -> {
                    try {
                        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
                        String message;
                        while ((message = console.readLine()) != null) {
                            out.write(message + "\n");
                            out.flush();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

